// pages/rentdevicelist/rentdevicelist.js
var util = require('../../utils/util.js'); 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    arr: [],
    brr: [],

    rentid: null,

    deviceid: null,
    devicename: null,
    deviceprovider: null,
    devicetype: null,
    amount: null,
    deviceowner: null,
    deviceownerid: null,
    devicedetail: null,
    deviceimage: null,
    devicerentdate: null,

    hostername: null,
    hosterid: null,

    rentamount: null,
    rentdate: null,

    takenhour: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    //1.获取token
    wx.request({
      url: "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential",
      data: {
        appid: getApp().globalData.appID,
        secret: getApp().globalData.appSecret
      },
      success: function (res) {
        console.log('access_token:', res.data.access_token)
        getApp().globalData.access_token = res.data.access_token;
      }
    })

    /* 初始化数据库 */
    const db = wx.cloud.database()
    db.collection('Devicerentlist').get
      ({
        success: res => {
          this.setData({
            arr: res.data
          });

        var length = this.data.arr.length
        var brr = this.data.arr
        for(var i = 0; i < length ; i ++){
          var temp = new Date(1000 * this.data.arr[i].rentdate)
          brr[i].rentdate = util.formatTime(temp)
        }
        this.setData({
          brr:brr
        })
          console.log('数据库查询成功:', res.data)
        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  //form bindsubmit
  havehandle: function (event) {

    var that = this
    console.log(event)

    this.setData
      ({
        rentid: event.currentTarget.dataset.rentid
      })

    /* 初始化数据库 */
    const db = wx.cloud.database()
    const _ = db.command

    db.collection('Devicerentlist').where
      ({
        _id: _.eq(this.data.rentid)
      })
      .get
      ({
        success: res => {
          this.setData(
            {
              deviceid: res.data[0].deviceid,
              rentamount: res.data[0].rentnum,
              hosterid: res.data[0].askerid,
              hostername: res.data[0].asker,
              rentdate: res.data[0].rentdate,
            }
          )



          db.collection('Device').where
            ({
              _id: _.eq(this.data.deviceid)
            })
            .get
            ({
              success: res => {
                this.setData(
                  {
                    devicename: res.data[0].name,
                    deviceprovider: res.data[0].provider,
                    amount: res.data[0].amount,
                    deviceowner: res.data[0].owner,
                    deviceownerid: res.data[0].ownerid,
                    devicedetail: res.data[0].adding,
                    deviceimage: res.data[0].image,
                    devicetype: res.data[0].dtype,
                    // collectionStatus: res.data[0].collectionStatus,
                    // collectionNum: res.data[0].collectionNum,
                    // bookrentrecord: res.data[0].rentrecord,
                    devicerentdate: res.data[0].rentdate,
                  }
                )
                console.log('数据库查询成功:', res.data)



                var numflag = 0
                var deviceownertem = this.data.deviceowner
                var deviceowneridtem = this.data.deviceownerid
                var length = deviceowneridtem.length
                var devicenum = this.data.amount
                var devicerentdatetem = this.data.devicerentdate
                var rentnumtem = this.data.rentamount




                devicenum = devicenum - rentnumtem

                for (var j = 0; j < length; j++) {
                  if (deviceowneridtem[j] == '空') {
                    console.log('devicenum', devicenum)
                    deviceowneridtem[j] = this.data.hosterid
                    deviceownertem[j] = this.data.hostername
                    devicerentdatetem[j] = this.data.rentdate
                    numflag = numflag + 1
                    console.log('numflag', numflag)

                    if (numflag == rentnumtem) {
                      this.setData
                        ({
                          devicerentdate: devicerentdatetem,
                          deviceowner: deviceownertem,
                          deviceownerid: deviceowneridtem,
                          amount: devicenum
                        })
                      break
                    }
                  }
                }

                db.collection('Devicerentlist').doc(this.data.rentid).remove({
                  success: res => {

                    const db = wx.cloud.database()
                    db.collection('Devicerentlist').get
                      ({
                        success: res => {
                          this.setData({
                            arr: res.data
                          });
                          var length = this.data.arr.length
                          var brr = this.data.arr
                          for (var i = 0; i < length; i++) {
                            brr[i].rentdate = new Date(1000 * this.data.arr[i].rentdate)
                          }
                          this.setData({
                            brr: brr
                          })
                          console.log('数据库查询成功:', res.data)
                        },
                        fail: err => {
                          wx.showToast({
                            icon: 'none',
                            title: '查询记录失败'
                          })
                          console.error('数据库查询失败', err)
                        }
                      })
                  },
                  fail: err => {
                    wx.showToast({
                      icon: 'none',
                      title: '删除失败',
                    })
                    console.error('[数据库] [删除记录] 失败：', err)
                  }
                })

                //2.向wanterid发送图书可借通知

                //准备模版数据
                console.log('getApp()_token:', getApp().globalData.access_token)
                let _access_token = getApp().globalData.access_token;
                let url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + _access_token;
                let temp = new Date(1000*this.data.rentdate)
                let sendtime = util.formatTime(temp)
                let _jsonData = {
                  access_token: _access_token,
                  // touser: 'ow6NN5VmfGWIwdAbO4kiyqMX8Y28',
                  touser: this.data.hosterid,
                  template_id: getApp().globalData.rentask,
                  form_id: event.detail.formId,
                  page: "pages/shelter/shelter",
                  data: {
                    "keyword1": { "value": this.data.hostername, "color": "#173177" },
                    "keyword2": { "value": this.data.devicename, "color": "#173177" },
                    "keyword3": { "value": sendtime, "color": "#173177" },
                    "keyword4": { "value": "您的借用申请已经通过。", "color": "#173177" }
                  },
                  //需要放大的关键字
                  // emphasis_keyword: 'keyword1.DATA'
                }
                //发送模版消息
                wx.request({
                  url: url,
                  data: _jsonData,
                  method: 'POST',
                  success: function (res) {
                    console.log(res)
                  },
                  fail: function (err) {
                    console.log('request fail ', err);
                  },
                  complete: function (res) {
                    console.log("request completed!");
                  }

                })

                console.log('完成')

                wx.cloud.callFunction
                  ({
                    // 云函数名称
                    name: 'rentdevice',
                    // 传给云函数的参数
                    data:
                    {
                      deviceid: this.data.deviceid,
                      deviceowner: this.data.deviceowner,
                      deviceownerid: this.data.deviceownerid,
                      hostername: this.data.hostername,
                      hosterid: this.data.hosterid,
                      devicenum: this.data.amount,
                      devicerentdate: this.data.devicerentdate,
                    },

                    success: function (res) {

                      console.log(res)
                    },

                    fail: console.error
                  })

                wx.showToast({
                  title: '借用成功',
                  icon: 'error',
                  duration: 2000          //提示的延迟时间
                })

                console.log('wxfu2')



              },
              fail: err => {
                wx.showToast({
                  icon: 'none',
                  title: '查询记录失败'
                })
                console.error('数据库查询失败', err)
              }
            })

        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '查询记录失败'
          })
          console.error('数据库查询失败', err)
        }
      })


  },

  //form bindreset
  neglect: function (event) {
    console.log('no event', event)

    var that = this
    console.log(event)

    this.setData
      ({
        rentid: event.currentTarget.dataset.rentid
      })

    var that = this


    /* 初始化数据库 */
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('Devicerentlist').doc(this.data.rentid).remove({
      success: res => {
        wx.redirectTo({                                   //页面无参数传递跳转
          url: '../rentdevicelist/rentdevicelist',
        })

        const db = wx.cloud.database()
        db.collection('Devicerentlist').get
          ({
            success: res => {
              this.setData({
                arr: res.data
              });
              console.log('数据库查询成功:', res.data)
            },
            fail: err => {
              wx.showToast({
                icon: 'none',
                title: '查询记录失败'
              })
              console.error('数据库查询失败', err)
            }
          })
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '删除失败',
        })
        console.error('[数据库] [删除记录] 失败：', err)
      }
    })

  },


})